import Taro, { } from '@tarojs/taro'
import { View, Text, Input, Button } from '@tarojs/components'
import { useEffect, useRef, useState ,forwardRef, useImperativeHandle} from 'react'
import styles from "./index.module.scss"
const customCarNumberInput=({ bindfocus },ref) =>{

    const [numbers, setNumbers] = useState([{
        value: '川',
        focus: false
    }, {
        value: '',
        focus: false
    }, {
        value: '',
        focus: false
    }, {
        value: '',
        focus: false
    }, {
        value: '',
        focus: false
    }, {
        value: '',
        focus: false
    }, {
        value: '',
        focus: false
    }, {
        value: '',
        focus: false,
        eco: true
    }])
    
    const click = (index) => {
        const _index = index;
        const _nums = [...numbers];
        numbers.map((item, index) => {
            item.focus = index == _index;
        });
        setNumbers(_nums)
        
        bindfocus(_index)
    }

    const change=(data)=> {
        const {
            index,
            value,
            remove
        } = data;
        const _nums = [...numbers];
        _nums[index].value = remove ? '' : value;

        const len = _nums.length;
        let nextIndex = remove ? index - 1 : index + 1;
        if (remove && nextIndex < 0) {
            nextIndex = len - 1;
        }
        if (!remove && nextIndex >= len)
            nextIndex = 0;

        _nums.forEach((item, idx) => {
            item.focus = idx == nextIndex;
        });
        setNumbers(_nums)
        bindfocus(nextIndex)
    }

    
  useImperativeHandle(ref, () => {
    return {
        click,
        change,
        numbers
    }
  })

    return (
        <View className={styles.custom_car_number_input}>
            {
                (numbers || []).map((item, index) => (
                    <View className={`${styles.cell} ${item.focus ? styles.focus : ''} ${item.eco ? styles.eco : ''}`} key={index} onClick={() => click(index)}  >
                        <Text className={styles.value} onClick={() => click(index)} >{item.value }</Text>
                        {item.focus && item.value == '' && <Text className={styles.cursor} ></Text>}
                    </View>
                ))
            }


        </View>
    )
}

export default forwardRef(customCarNumberInput) 
